<?php
namespace App\Http\Controllers\User;

use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use App\library\UtilFunction;
use App\Http\Components\UserComponent;
use App\Http\Components\RongCloudComponent;

use App\Models\UserProfileModel;

use App\library\UploadFile;

/**
 * 上传头像
 */
class UploadAvatarController extends UserController{

    public function __construct(){
        parent::__construct();        
    }

    /*版本控制，对应app版本跳转对应接口*/
    public function version_invoke(Request $request){
        $appversion = $request->input('appversion');
        $apptype = $request->input('apptype');
        if ($appversion && $apptype) {
            try{
                return $this->upload_avatar($request);
            }catch(\Exception $e){
                return $this->json('0','系统错误'.$e->getMessage());
            }
        }else{
            return $this->json('102','该app版本下无此接口，请更新app');
        }
    }

    /**
     * 上传头像
     * @param $coder_id 用户id
     * @return 
     */
    public function upload_avatar(Request $request){
        $path_url =  dirname(dirname(dirname(dirname(dirname(__FILE__)))))."/public/avatar";
        $user = UserComponent::check_token($request);
        $user_id = $user['user_id'];
        $avatar_auth  = $request->input('avatar_auth');
        $avatar =  $request->input('avatar');
        if(empty($avatar)){
            return $this->json('0','图片文件为空!');
        }
        $avatar_img = base64_decode($avatar);
        $img = imagecreatefromstring($avatar_img);
        $filename = $user_id.rand(1000,9999).".png";
        imagepng($img,$path_url."/".$filename);
        imagedestroy($img);

        $user_profile= UserProfileModel::where('user_id',$user_id)->first();

        if($user_profile){
            $user_profile->avatar = "/avatar/".$filename;
            if($avatar_auth == 1){
                if($user_profile->avatar_auth != 1){
                    UserProfileModel::where("user_id",$user_id)->increment("credit_num",5);
                }
                $user_profile->avatar_auth = 1;
            }
            if(empty($user_profile->nick_name)){
                $user_profile->nick_name = "ID：".$user_id;
            }
            $avatar_url = UtilFunction::getUrlImg("/avatar/".$filename);
            //注册融云
            if(empty($user_profile->message_token)){
                $message_token = RongCloudComponent::register($user_id,$user_profile->nick_name,$avatar_url);
                $user_profile->message_token = $message_token;
            }else{
                RongCloudComponent::update($user_id,$user_profile->nick_name,$avatar_url);
            }
            $user_profile->saveOrFail();
            return $this->json('1','上传头像成功',$avatar_url);
        }else{
            return $this->json('0','无法查询到对应用户信息1');
        }

    }
}
